import type { App } from 'vue'
import type { I18n, I18nOptions } from 'vue-i18n'

import { useLocaleStoreWithOut } from '@fl/store/modules/locale'
import { createI18n } from 'vue-i18n'

import { setHtmlPageLang } from './helper'

// eslint-disable-next-line import/no-mutable-exports
export let i18n: ReturnType<typeof createI18n>

async function createI18nOptions(): Promise<I18nOptions> {
    const localeStore = useLocaleStoreWithOut()
    const locale = localeStore.getCurrentLocale
    const localeMap = localeStore.getLocaleMap
    const defaultLocal = await import(`../../../../../packages/locales/${locale.lang}.ts`)
    const message = defaultLocal.default ?? {}

    setHtmlPageLang(locale.lang)

    localeStore.setCurrentLocale({
        lang: locale.lang,
    // elLocale: elLocal
    })

    return {
        availableLocales: localeMap.map(v => v.lang),
        fallbackLocale: locale.lang,
        legacy: false,
        locale: locale.lang,
        messages: {
            [locale.lang]: message,
        },
        missingWarn: false,
        silentFallbackWarn: true,
        silentTranslationWarn: true,
        sync: true,
    }
}

export async function setupI18n(app: App<Element>) {
    const options = await createI18nOptions()
    i18n = createI18n(options) as I18n
    app.use(i18n)
}
